#!/usr/bin/python
def query():
    """return user's query, a English word. If nor valid, 
    this function will end the program calling it."""
    import sys
    w = ''
    try:
        w = sys.argv[1]
    except IndexError:
        print 'You shouild input a word'
        exit()
    return w

def html_text( line ):
    """extract all html tags in a line, and return the rest text"""
    import re
    ex = re.compile( r'<[^<]+>' )
    return ex.sub( '', line )


class ExBlock:
    def __init__( self ): 
        self.reset()
    def reset( self ):
        self.chinese = None
        self.eng = None
        self.chi = None
    def display( self ):
        import sys
        sys.stdout.write( '[1;36m'+self.chinese+'[m' )
        if self.eng:
            sys.stdout.write( '[1;33m     '+self.eng+'[m' )
            sys.stdout.write( '[1;32m     '+self.chi+'[m' )
        print 
class WebDict:
    def __init__( self, url_, site_strategy ):
        """get url and approach
             url: url-encoded
             process: a functor, getting a html page and outputting a list of explainations"""
        self.url = url_
        self.process = site_strategy
    
    def __answer( self, url ):
        import urllib
        try:
            page = urllib.urlopen( url )
        except Exception, e:
            print "URL openning error: %s" % e     
            exit()
        return page
             
    def query( self, w ):
        self.raw_content = self.__answer( self.url + w )
        ex_blocks = self.process( self.raw_content )
        if ex_blocks == []: 
            print('[5;31m'+"There is no definition of this word"+'[m')
            exit()
        i = 0
        for ex_block in ex_blocks:
            import sys
            i += 1
            sys.stdout.write( '[36m'+str(i)+'. [m' )
            ex_block.display()

def yahoo_way( page ):
    import re, sys, copy
    while True:
        try:
            ex_blocks = []
            ex_block = ExBlock()
            for line in page:
                if re.search( r'pexplain', line ):
                    if ex_block.chi: ex_block.reset()
                    if ex_block.chinese:
                        ex_blocks.append( copy.deepcopy(ex_block) )
                        ex_block.reset()
                    ex_block.chinese = html_text( line )
                if ex_block.chinese and re.search( r'peng', line ):
                    ex_block.chi = None
                    ex_block.eng = html_text( line )
                if ex_block.chinese and re.search( r'pchi', line ):
                    ex_block.chi = html_text( line )
                if ex_block.chinese and ex_block.eng and ex_block.chi:
                    ex_blocks.append( copy.deepcopy(ex_block) )
                    ex_block.reset()
        except UnicodeError:
            continue
        break 
    if ex_block.chinese: ex_blocks.append( copy.deepcopy(ex_block) )
    return ex_blocks

if __name__ == '__main__':
    print("querying...please wait...\n")
    #web_dict = WebDict( 'http://tw.dictionary.yahoo.com/search?ei=UTF-8&p=', yahoo_way)
    web_dict = WebDict( 'http://tw.dictionary.yahoo.com/dictionary?p=hello', yahoo_way)
    w = query()
    web_dict.query( w )

